# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(scatterplot3d)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleColDf <- read.csv(opt$sc, header = T, stringsAsFactors = F, comment.char = "") %>%
select(c("ClassNote", "col"))

parent <- "./"
createWhenNoExist(parent)
modelFileName <- paste0(parent, "/PLSDA_R2X_R2Y_Q2.csv")
dataFileName <- paste0(parent, "/PLSDA_Score.csv")
fileName <- paste0(parent, "/PC123_Score_3D.pdf")

pdf(fileName, width = 8, height = 8)

sampleInfo <- read_csv(opt$g) %>%
    select(c("SampleID", "ClassNote")) %>%
    as.data.frame()

sampleInfo

plotData <- read_csv(dataFileName) %>%
    rename(SampleID = X1) %>%
    left_join(sampleInfo, by = c("SampleID")) %>%
    left_join(sampleColDf, by = c("ClassNote"))

head(plotData)
modelDf <- read.csv(modelFileName, header = T, row.names = 1)
modelDf

opar <- par(no.readonly = TRUE)
par(family = "Times")

scatterplot3d(plotData$C1, plotData$C2, plotData$C3, color = plotData$col, main = "", pch = 20, col.axis = "grey",
mar = c(5, 3, 1, 3) + 0.1, cex.symbols = 6, xlab = paste0("Component 1 (", modelDf["C1", "R2X"] * 100 , "%)"),
ylab = paste0("Component 2 (", modelDf["C2", "R2X"] * 100 , "%)"), zlab = paste0("Component 3 (", modelDf["C3", "R2X"] * 100 , "%)"),
angle = 60, cex.lab = 2, cex.axis = 1.5)

par(opar)

dev.off()